/*
 * Copyright 2011 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.orkut.androidexample;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;

import com.google.orkut.client.api.Address;
import com.google.orkut.client.api.BatchTransaction;
import com.google.orkut.client.api.GetProfileTx;
import com.google.orkut.client.api.OrkutAdapterException;
import com.google.orkut.client.api.OrkutPerson;
import com.google.orkut.orkroid.Orkroid;
import com.google.orkut.orkroid.OrkroidTask;

public class ShowProfileActivity extends Activity implements OrkroidTask.Listener, View.OnClickListener {
	String userId;
	WebView webView;
	Button scrapButton, closeButton;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showprofileactivity);
		userId = getIntent().getStringExtra("userid");
		webView = (WebView) findViewById(R.id.webview);
		webView.loadData("<html><body><br><br><br><div align='center'>Loading Profile...</div></body></html>", 
				"text/html", "utf-8");
		
		try {
			BatchTransaction btx = Orkroid.getOA().newBatch();
			GetProfileTx tx = userId.equals("") ?
					Orkroid.getOA().getProfileTF().getSelfProfile() :
					Orkroid.getOA().getProfileTF().getProfileOf(userId);
			tx.alsoGetAddress();
			tx.alsoGetBirthday();
			tx.alsoGetEmails();
			tx.alsoGetGender();
			tx.alsoGetName();
			tx.alsoGetPhoneNumbers();
			tx.alsoGetProfileUrl();
			tx.alsoGetStatus();
			tx.alsoGetThumbnailUrl();
			btx.add(tx);
			OrkroidTask.execute("",btx,this);
		}
		catch (OrkutAdapterException ex) {
			onOrkroidTaskFinished("", null, ex);
		}
		
		scrapButton = (Button) findViewById(R.id.scrapbutton);
		closeButton = (Button) findViewById(R.id.closebutton);
		
		closeButton.setOnClickListener(this);
		
		if (userId.equals(""))
			scrapButton.setEnabled(false);
		else
		    scrapButton.setOnClickListener(this);
	}
	
	public void onClick(View target) {
		if (target == closeButton) { finish(); return; }
		else if (target == scrapButton) {
			Intent i = new Intent(this, ScrapActivity.class);
			i.putExtra("userid", userId);
			startActivity(i);
		}
	}
	
	public void showError(String err) {
		webView.loadData("<html><body><br><br><br><div align='center'>" + err + "</div></body></html>", "text/html", "utf-8");
	}
	
	public void onOrkroidTaskFinished(String tag, BatchTransaction btx,	Exception exc) {
		if (btx == null) { showError("Error requesting profile."); return; }
		if (exc != null) { showError("Error loading profile."); return;	}
		
		GetProfileTx tx = (GetProfileTx) btx.getTransaction(0);
		OrkutPerson p = (OrkutPerson) tx.getProfile();
		
		if (p == null) { showError("No profile received."); return; }
		
		StringBuilder sb = new StringBuilder();
		sb.append("<html><body style='background: #000000; color: #a0a0a0'>");
		sb.append("<table><tr><td><img src='" + p.getThumbnailUrl() + "'></td>");
		sb.append("<td><span style='color: #a9c639; font-size: 14pt'><b>" + 
				p.getDisplayName() + "</b></span></td></tr>");
		
		sb.append("<tr><td><span style='color: #a9c639'><em>Status</em></span><td>");
		sb.append(p.getStatus());
		sb.append("</td><tr>");

		sb.append("<tr><td><span style='color: #a9c639'><em>Gender</em></span><td>");
		sb.append(p.getGender());
		sb.append("</td><tr>");

		sb.append("<tr><td><span style='color: #a9c639'><em>E-Mails</em></span><td>");
		int i;
		for (i = 0; i < p.getEmailCount(); i++)
			sb.append((i > 0 ? ", " : "") + p.getEmail(i));
		sb.append("</td><tr>");

		sb.append("<tr><td><span style='color: #a9c639'><em>Phones</em></span><td>");
		for (i = 0; i < p.getPhoneNumberCount(); i++)
			sb.append((i > 0 ? ", " : "") + p.getPhoneNumber(i));
		sb.append("</td><tr>");
		
		sb.append("<tr><td><span style='color: #a9c639'><em>Birthday</em></span><td>");
		if (p.getBirthday() > 0) sb.append(new Date(p.getBirthday())).toString();
		else sb.append("not available");
		sb.append("</td><tr>");

		sb.append("<tr><td><span style='color: #a9c639'><em>Address</em></span><td>");
		Address addr = p.getAddress();
		if (addr == null)
			sb.append("not available");
		else {
			String locality = addr.getLocality();
			String country = addr.getCountryCode();
			String zip = addr.getPostalCode();
			String region = addr.getRegion();
			if (locality.length() > 0) locality = "<b>Locality:</b> " + locality + "<br>";
			if (country.length() > 0) country = "<b>Country:</b>" + country + "<br>";
			if (zip.length() > 0) zip = "<b>Postal code:</b>" + zip + "<br>";
			if (region.length() > 0) region = "<b>Region:</b>" + region + "<br>";
			sb.append(locality);
			sb.append(region);
			sb.append(country);
			sb.append(zip);
		}
		
		sb.append("</td></tr>");
		
		sb.append("</table></body></html>");
		webView.loadData(sb.toString(), "text/html", "utf-8");
	}
	
	private static String nullsafe(String s) { return s == null ? "not available" : s; }

}
